import * as actionTypes from './actionTypes';
import {Toast} from 'antd-mobile';
// 同步动作
const mutations = {
  setUser: value => ({
    type: actionTypes.SET_USERNAME,
    userName: value
  })
};

// 异步操作
const actions = {
  /**
   * 用户注册
   * @param {object} payload
   */
  RegisterAct: payload => {
    return (dispatch,getState) => {
      Toast.loading('注册中...',0);
      fetch("http://106.52.37.222:3000/users",{
        method: "POST",
        body: JSON.stringify({
          name: payload.name,
          password: payload.password
        }),
        headers: {
          "Content-Type": "application/json"
        }
      })
      .then(response => response.json())
      .then(res => {
        Toast.hide();
        console.log(res);
        Toast.success('注册成功',4);
        payload.props.history.replace('/login');
      })
    }
  },

  /**
   * 用户登录
   * @param {object} payload
   */
  LoginAct: payload => {
    return (dispatch,getState) => {
      let props = payload.props;
      Toast.loading('登录中',0);
      fetch(`http://106.52.37.222:3000/users?name=${payload.name}&password=${payload.password}`)
      .then(response => response.json())
      .then(res => {
        Toast.hide();
        // console.log(res);
        if(res.length > 0) {
          Toast.success('登录成功',2);
          window.localStorage.setItem('username',JSON.stringify(payload.name));
          dispatch(mutations.setUser(payload.name));
          // 跳转到首页或之前想要去的页面
          let redirect = props.location.search;
          redirect = redirect.replace('?',''); // key1=value&key2=value
          let arr = redirect.split('&');
          let obj = {};
          arr.forEach(element => {
            let tmp = element.split("=");
            obj[tmp[0]] = tmp[1];
          });
          redirect = obj.redirect || "/home";
          props.history.replace(redirect);
        }
        else {
          Toast.fail('用户名或密码错误',4);
        }
      })
    }
  },
  /**
   * 登出操作
   */
  LogoutAct: (props) => {
    return (dispatch,getState) => {
      window.localStorage.removeItem('username');
      Toast.success('退出成功',2);
      dispatch(mutations.setUser(''));
      props.history.replace('/home');
    }
  }
}

export default actions;
